package com.jourwon.springcloud.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.ArrayUtils;
import com.jourwon.springcloud.bean.MyUser;
import com.jourwon.springcloud.bean.Result;
import com.jourwon.springcloud.bean.SysUser;
import com.jourwon.springcloud.bean.UserInfo;
import com.jourwon.springcloud.common.OauthConstants;
import com.jourwon.springcloud.common.SecurityConstants;
import com.jourwon.springcloud.feign.RemoteUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @description:
 * @author: luojm
 * @create: 2020-05-15 11:49
 */
@Slf4j
@Service
@AllArgsConstructor
public class MyUserDetailsServiceImpl implements MyUserDetailsService{
    private final RemoteUserService remoteUserService;
    private final CacheManager cacheManager;

    /**
     * 用户密码登录
     *
     * @param username 用户名
     * @return
     */
    @Override
    public UserDetails loadUserByUsername(String username) {
        Cache cache = cacheManager.getCache("user_details");
        if (cache != null && cache.get(username) != null) {
            return (MyUser) Objects.requireNonNull(cache.get(username)).get();
        }
        Result<UserInfo> result = remoteUserService.info(username);
        UserDetails userDetails = getUserDetails(result);
        cache.put(username, userDetails);
        return userDetails;
    }

    /**
     * 构建userdetails
     *
     * @param result 用户信息
     * @return
     */
    private UserDetails getUserDetails(Result<UserInfo> result) {
        if (result == null || result.getData() == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        UserInfo info = result.getData();
        Set<String> authoritiesSet = new HashSet<>();
        if (ArrayUtils.isNotEmpty(info.getRoles())) {
            // 获取角色
            Arrays.stream(info.getRoles()).forEach(role -> authoritiesSet.add(SecurityConstants.ROLE + role));
            // 获取资源
            authoritiesSet.addAll(Arrays.asList(info.getPermissions()));

        }
        Collection<? extends GrantedAuthority> authorities
                = AuthorityUtils.createAuthorityList(authoritiesSet.toArray(new String[0]));
        SysUser user = info.getSysUser();

        // 构造security用户
        return new MyUser(user.getUserId(), user.getUsername(), user.getPassword(),
                StrUtil.equals(user.getLockFlag(), OauthConstants.STATUS_NORMAL),
                true, true, true, authorities);
    }

    /**
     * 根据社交登录code 登录
     *
     * @param inStr TYPE@CODE
     * @return UserDetails
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserBySocial(String inStr) throws UsernameNotFoundException {
        return getUserDetails(remoteUserService.social(inStr));
    }
}
